<?php
namespace app\admin\controller;
use app\__MODULE__\model\{StoreCoupon,Goods,StoreCategory,StoreCouponIssue};
use  think\facade\Db;
use app\common\BaseController;

class CouponTemplate extends BaseController{
    

    /**
     * 首页
     */
    public function index(){
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        $where[] = ['is_del','=',0];
        if(isset($search["title"]) && $search["title"]!="") $where[] = ["title","=",$search["title"]];
        $goods    = Goods::where('is_del',0)->where('is_show',1)->field('id,store_name')->select();
        $category = StoreCategory::field('id,cate_name')->select();
        $query    = StoreCoupon::where($where);
        $total    = $query->count();
        $data     = $query->page($page, $limit)->order('sort desc')->append(['type_name'])->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'goods' => $goods,
            'category' => $category
        ]);
    }

        /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = StoreCoupon::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }
    /**
     * 添加优惠券
     * @return [type] [description]
     */
    public function create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'title' => 'require',
                'coupon_price' => 'require'
            ], [
               'title.require' =>'请输入优惠券名称',
                'coupon_price.require' =>'请输入优惠券面额'
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getError());
        }
           $data['add_time']  = time();
           if(StoreCoupon::create($data)) json_response(1,'操作成功');
           json_response(0,'操作失败');
    }



    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'title' => 'require',
                'coupon_price' => 'require'
            ], [
                'id.require'  => 'ID不得为空',
               'title.require' =>'请输入优惠券名称',
                'coupon_price.require' =>'请输入优惠券面额'
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getError());
        }
        $id = \param_check('id');
           $data = request()->post();
           if(StoreCoupon::update($data)) json_response(1,'操作成功');
           json_response(0,'操作失败');
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function delete(){
        $id = param_check('ids');
        if(!$StoreCoupon = StoreCoupon::find($id)) json_response(0,'不存在');
        $StoreCoupon->is_del = 1;
        if($StoreCoupon->save()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

    /**
     * 发布
     * @return [type] [description]
     */
    public function issue(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'start_time' => 'require',
                'end_time' => 'require',
            ], [
                'id.require'      => 'id不得为空',
                'start_time.require' =>'请选择开始时间',
                'end_time.require' =>'请选择结束时间'
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        Db::startTrans();
        try {
            if(strtotime($data['end_time']) <= strtotime($data['start_time']))  exception('结束时间不得小于开始时间');
            if($data['is_permanent'] == 0 && $data['total_count']<=0)           exception('请输入发布数量');
            if($data['is_full_give'] == 1 && $data['full_reduction']<=0)        exception('请输入满赠金额');
            $data['start_time']      = strtotime($data['start_time']);
            $data['end_time']        = strtotime($data['end_time']);
            $data['add_time']        = time();
            $res = StoreCouponIssue::setIssue($data['id'], $data['total_count'], $data['start_time'],$data['end_time'], $data['total_count'], $data['status'], $data['is_permanent'],$data['full_reduction'], $data['is_full_give']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            json_response(0,$e->getMessage());
        }
        json_response(1,'操作成功');
         
    }


}